<template>
  <div class="myitem-main">
    <input :id="todo.id" type="checkbox" :checked="todo.done" @click="updateTodo()"/>
    <label v-show="!todo.isEdit" :for="todo.id">{{ todo.title }}</label>
    
    <!-- 编辑框 -->
    <input 
        :value="todo.title"
        v-show="todo.isEdit" 
        ref="editInput" 
        type="text"
        @keyup.enter="handleBlur(todo, $event)" 
        @blur="handleBlur(todo, $event)"
    >

    <!-- 删除按钮 -->
    <button @click="delTodo()">删除</button>
    <!-- 编辑按钮 -->
    <button v-show="!todo.isEdit" id="editButton" @click="handelEdit(todo)">编辑</button>
  </div>
</template>

<script>
import pubsub from 'pubsub-js'


export default {
    name: "MyItem",
    props: ['todo'],
    methods: {
        // 删除该todo
        delTodo() {
            // 发布消息
            pubsub.publish('delTodo', this.todo.id)
        },
        updateTodo() {
            pubsub.publish('updateTodoCheck', this.todo.id)
        },
        // 按下编辑按钮执行
        handelEdit(todo) {
            if (Object.hasOwnProperty.call('todo', 'isEdit')) {
                this.isEdit = true
            } else {
                this.$set(todo, 'isEdit', true)
            }
            this.$nextTick(function() {
                this.$refs.editInput.focus()
            })
        },
        // 提交编辑结果
        handleBlur(todo, e) {
            todo.isEdit = false
            if (e.target.value.trim() == '') {
                return alert('请写点什么吧...')
            }
            
            this.$bus.$emit('updateTodo', todo.id, e.target.value)
        }
    }
}
</script>

<style scoped>
    #editButton {
        background-color: #2b9620;
        margin-right: 20px;
    }
    label {
        font-weight: bold;
        cursor: pointer;
    }
    button {
        float: right;
    }
    input[type="checkbox"] {
        display: inline-block;
        margin-right: 3px;
    }

    input[type='text'] {
        padding: 3px;
        font-weight: bold;
    }

    .myitem-main {
        border: 1px solid #c9c9c9;
        padding: 5px;
        border-radius: 2px;
        height: 25px;
    }

    .myitem-main:hover {
        background-color: #f2f2f2;
    }
    .myitem-main:hover button {
        visibility: visible;
    }
</style>